package com.lans.table;

import java.util.Scanner;

/**
 * @author: lans
 * @date: 2025/3/8
 * @name: 刘宇
 */
public class HashTable {

    private StudentLinkedList[] studentLinkedList;

    private int size;

    public HashTable(int size) {
        this.size = size;
        studentLinkedList = new StudentLinkedList[size];
        for (int i = 0; i < size; i++) {
            studentLinkedList[i] = new StudentLinkedList();
        }
    }

    /**
     * 往哈希表中添加学生信息
     *
     * @param student
     */
    public void add(Student student) {
        int hashValue = hashValue(student.id);
        studentLinkedList[hashValue].add(student);
    }

    /**
     * 获取哈希表的索引值
     *
     * @param id
     * @return
     */
    public int hashValue(int id) {
        return id % size;
    }

    /**
     * 查看所有信息
     */
    public void list() {
        for (int i = 0; i < size; i++) {
            studentLinkedList[i].list();
        }
    }

    public void findByStduentId(int id) {
        int hashValue = hashValue(id);
        Student byStudentId = studentLinkedList[hashValue].findByStudentID(id);
        if (byStudentId != null) {
            System.out.printf("查询到在索引位置是 %d 链表中找到了此学生,名称是 %s ", hashValue, byStudentId.name);
        } else {
            System.out.println("未找到该学生");
        }
    }

    public static void main(String[] args) {
        HashTable hashTable = new HashTable(10);
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("add 添加学员");
            System.out.println("list 显示");
            System.out.println("find 查找学员");
            System.out.println("exit 退出操作");
            String input = scanner.next();
            switch (input) {
                case "add":
                    System.out.println("请输入学生id");
                    int id = scanner.nextInt();
                    System.out.println("请输入学生名称");
                    String name = scanner.next();
                    Student student = new Student(id, name);
                    hashTable.add(student);
                    System.out.println("添加成功!");
                    System.out.println();
                    break;
                case "list":
                    hashTable.list();
                    break;
                case "find":
                    System.out.println("请输入学生id编号:");
                    int findId = scanner.nextInt();
                    hashTable.findByStduentId(findId);
                    break;
                case "exit":
                    scanner.close();
                    System.exit(0);
                    break;
            }
        }
    }

}